import random
from django import http
from django.views.generic import View
from django_redis import get_redis_connection

from meiduo_mall.utils import constants
from verifies.libs.captcha.captcha import captcha
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer
from django.conf import settings


class ImageCodeView(View):

    def get(self, request, img_code_id):
        print('------------', img_code_id)
        name, txt, img = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_code_%s' % img_code_id, constants.IMG_CODE_EXIST_TIME, txt)

        return http.HttpResponse(img)


class PhoneCodeView(View):
    def get(self, request, phone):
        data = request.GET
        redis_conn = get_redis_connection('verify_code')
        # 密码找回
        access_token = data.get('access_token')
        if access_token:
            access_token = access_token.encode()
            serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=300)
            try:
                serializer.loads(access_token)
            except:
                return http.JsonResponse({'message': 'access_token已过期'})

        else:

            img_code = data.get('image_code').lower()
            img_code_id = data.get('image_code_id')

            redis_img_code = redis_conn.get('img_code_%s' % img_code_id)
            # 检验图片验证码是否过期
            if not redis_img_code:
                return http.JsonResponse({'code': '4001', 'errmsg': '验证码已过期'})
            redis_img_code = redis_img_code.decode().lower()
            redis_conn.delete('img_code_%s' % img_code_id)

            if img_code != redis_img_code:
                return http.JsonResponse({'code': '4001', 'errmsg': '验证码输入错误'})

        # 判断是否频繁请求手机验证码
        if redis_conn.get('sms_flag_%s' % phone):
            print('请求频繁')
            return http.JsonResponse({'msg_error': '请求频繁'}, status=400)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print('-' * 20, 'sms', sms_code)

        # ccp = CCP()
        # 给手机发送验证码
        # ccp.send_template_sms(phone, [sms_code, 5], 1)
        from celery_tasks.sms.tasks import send_msg
        send_msg.delay(phone, sms_code, 5)

        redis_pip = redis_conn.pipeline()  # 开启redis管道（事务）
        redis_pip.setex('sms_code_%s' % phone, constants.SMS_CODE_EXIST_TIME, sms_code)
        redis_pip.setex('sms_flag_%s' % phone, constants.SMS_CODE_EXIST_TIME, 1)
        redis_pip.execute()

        return http.JsonResponse({'code': '0'})
